package cn.tedu.straw.api.question.controller;

import cn.tedu.straw.api.question.dto.PostCommentDTO;
import cn.tedu.straw.api.question.ex.InvalidParameterException;
import cn.tedu.straw.api.question.service.ICommentService;
import cn.tedu.straw.commons.security.LoginUserInfo;
import cn.tedu.straw.commons.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2020-11-11
 */
@RestController
@RequestMapping("/portal/comment")
@Slf4j
public class CommentController {

    @Autowired
    ICommentService commentService;

    // http://localhost/api-question/portal/comment/post?answerId=1&content=TestComment
    @RequestMapping("/post")
    public R<Void> post(@Valid PostCommentDTO postCommentDTO, BindingResult bindingResult,
                        @AuthenticationPrincipal LoginUserInfo loginUserInfo) {
        log.debug("发表评论，客户端提交的数据：{}", postCommentDTO);
        log.debug("发表评论，当前登录的用户信息：{}", loginUserInfo);

        if (bindingResult.hasErrors()) {
            String errorMessage = bindingResult.getFieldError().getDefaultMessage();
            throw new InvalidParameterException(errorMessage);
        }

        Integer userId = loginUserInfo.getUserId();
        String userNickName = loginUserInfo.getNickName();
        commentService.post(postCommentDTO, userId, userNickName);
        return R.ok();
    }

}
